<template>
  <div class="image-upload">
    <el-upload
      ref="uploadRef"
      :action="uploadUrl"
      :headers="uploadHeaders"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-remove="handleRemove"
      :file-list="fileList"
      :limit="1"
      list-type="picture-card"
      :auto-upload="true"
    >
      <el-icon class="upload-icon"><Plus /></el-icon>
      <template #tip>
        <div class="upload-tip">
          {{ tip || "支持 jpg、png、jpeg 格式，文件大小不超过 5MB" }}
        </div>
      </template>
    </el-upload>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="600px">
      <img :src="previewUrl" alt="预览图片" style="width: 100%; height: auto" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  tip: {
    type: String,
    default: "",
  },
});

const emit = defineEmits(["update:modelValue"]);

// 响应式数据
const uploadRef = ref();
const previewVisible = ref(false);
const previewUrl = ref("");
const fileList = ref([]);

// 计算属性
const uploadUrl = computed(() => {
  return `${
    import.meta.env.VITE_API_BASE_URL || "http://localhost:3000/api"
  }/upload/id-card`;
});

const uploadHeaders = computed(() => {
  const token = localStorage.getItem("token");
  return token ? { Authorization: `Bearer ${token}` } : {};
});

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal && fileList.value.length === 0) {
      fileList.value = [
        {
          name: "身份证照片",
          url: newVal.startsWith("http")
            ? newVal
            : `http://localhost:3000${newVal}`,
        },
      ];
    } else if (!newVal) {
      fileList.value = [];
    }
  },
  { immediate: true }
);

// 上传前检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt5M) {
    ElMessage.error("图片大小不能超过 5MB!");
    return false;
  }
  return true;
};

// 上传成功
const handleSuccess = (response, file) => {
  if (response.url) {
    emit("update:modelValue", response.url);
    ElMessage.success("图片上传成功");
  } else {
    ElMessage.error("上传失败，请重试");
  }
};

// 上传失败
const handleError = (error) => {
  console.error("上传失败:", error);
  ElMessage.error("图片上传失败，请重试");
};

// 移除文件
const handleRemove = (file) => {
  emit("update:modelValue", "");
  ElMessage.success("图片已移除");
};

// 预览图片
const handlePreview = (file) => {
  previewUrl.value = file.url;
  previewVisible.value = true;
};
</script>

<style lang="scss" scoped>
.image-upload {
  .upload-tip {
    font-size: 12px;
    color: #999;
    margin-top: 8px;
    text-align: center;
  }

  .upload-icon {
    font-size: 28px;
    color: #8c939d;
  }
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 120px;
}
</style>
